package com.larry.collect.interceprot;

import com.alibaba.fastjson.JSON;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;

/**
 * @ProjectName hadoop
 * @Author larry
 * @Date 12:40 2021/12/6
 * @Description Flume拦截器
 **/
public class ETLLogInterceptor implements Interceptor {

    @Override
    public void initialize() {

    }

    @Override
    public Event intercept(Event event) {
        String body = new String(event.getBody(), StandardCharsets.UTF_8);
        try {
            JSON.parseObject(body);
        } catch (Exception e) {
            return null;
        }
        return event;
    }

    /**
     * 迭代器移除元素
     * @param events
     * @return
     */
    @Override
    public List<Event> intercept(List<Event> events) {
        Iterator<Event> iterator = events.iterator();
        while (iterator.hasNext()){
            Event event = iterator.next();
            Event res = intercept(event);
            if (res == null){
                iterator.remove();
            }
        }
        return events;
    }

    @Override
    public void close() {

    }

    public static class MyBuilder implements Builder{

        @Override
        public Interceptor build() {
            return new ETLLogInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }
}
